#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <unordered_map>

#include "Log.hpp"

using namespace std;

namespace pxt
{
    const string unknow = "unknow";
    const string mydict = "./recource/dict.txt";
    const string sep = " ";

    class Translate
    {
    public:
        Translate(string dict_path = mydict)
            : _dict_path(dict_path)
        {
            LoadDict();
            Parse();
        }

        void LoadDict()
        {
            ifstream in(_dict_path);
            string line;

            while (getline(in, line))
            {
                lines.push_back(line);
            }

            in.close();
            lg.LogMessage(Debug, "Load dict_txt success, path: %s\n", _dict_path.c_str());
        }

        void Parse()
        {
            for (auto &line : lines)
            {
                auto pos = line.find(sep);
                if (pos == string::npos)
                    continue;

                else
                {
                    string word = line.substr(0, pos);
                    string chinese = line.substr(pos + sep.size());
                    _dict.insert(make_pair(word, chinese));
                }
            }
            lg.LogMessage(Debug, "Parse dict_txt success, path: %s\n", _dict_path.c_str());
        }

        void debug()
        {
            // for(auto &line : lines)
            // {
            //     cout << line << endl;
            // }

            for (auto &elem : _dict)
            {
                cout << elem.first << " : " << elem.second << endl;
            }
        }

        string Excute(const string &word)
        {
            auto iter = _dict.find(word);
            if (iter == _dict.end())
                return unknow;
            else
                return _dict[word];
        }

        ~Translate()
        {
        }

    private:
        string _dict_path;
        unordered_map<string, string> _dict;
        vector<string> lines;
    };
}